package com.jinly.ryder.common.service.impl;


import com.jinly.ryder.common.service.TemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;

@Slf4j
@Service
public class TemplateServiceImpl implements TemplateService {

    private Map<String, String> templateMap = new HashMap<>();

    @Override
    public String getLocalResult(String localFile, Map<String, String> paramMap) {
        String template = getTemplate(localFile);
        String result = template;
        for (Map.Entry<String, String> param : paramMap.entrySet()) {
            result = result.replaceAll("#\\{" + param.getKey() + "}", Matcher.quoteReplacement(param.getValue()));
        }
        return result;
    }

    private String getTemplate(String localFile) {
        if (!templateMap.containsKey(localFile)) {
            BufferedReader in = null;
            try {
                in = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(localFile)));
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = in.readLine()) != null) {
                    buffer.append(line).append("\n");
                }
                templateMap.put(localFile, buffer.toString());
            } catch (Exception e) {
                log.error("读取文件失败{}", localFile);
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception e) {
                }
            }
        }
        return templateMap.get(localFile);
    }
}
